import { Controller } from 'egg';
import { RESULT_CODE } from '../utils/constants/code';

export default class ExclusiveRestaurantOrderController extends Controller {
  // （1）添加订单：接收 [{ dish_id, quantity }]
  async addOrder() {
    const { ctx } = this;

    const { list, remark } = ctx.request.body;
    if (!Array.isArray(list) || list.length === 0) {
      ctx.throw(RESULT_CODE.FAIL, '参数格式错误');
    }
    // 基础校验
    list.forEach((it: any) => {
      if (!it || !it.dish_id || it.quantity === undefined) {
        ctx.throw(RESULT_CODE.FAIL, 'dish_id 与 quantity 必填');
      }
    });

    try {
      const result = await ctx.service.exclusiveRestaurantOrderService.createOrder(
        list.map((i: any) => ({ dish_id: Number(i.dish_id), quantity: Number(i.quantity) })),
        remark,
      );
      ctx.body = { code: RESULT_CODE.SUCCESS, message: '下单成功', data: result };
    } catch (error: any) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // （2）取消订单
  async cancelOrder() {
    const { ctx } = this;
    const { id } = ctx.request.body || {};
    if (!id) ctx.throw(RESULT_CODE.FAIL, 'id 不能为空');

    try {
      const ret = await ctx.service.exclusiveRestaurantOrderService.cancelOrder(Number(id));
      ctx.body = { code: RESULT_CODE.SUCCESS, message: ret.message, data: null };
    } catch (error: any) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // （3）处理订单（修改状态：accepted/rejected）
  async updateOrderStatus() {
    const { ctx } = this;
    const { id, status } = ctx.request.body || {};
    if (!id || !status) ctx.throw(RESULT_CODE.FAIL, 'id 与 status 不能为空');
    if (!['accepted', 'rejected'].includes(status)) ctx.throw(RESULT_CODE.FAIL, 'status 不合法');

    try {
      const ret = await ctx.service.exclusiveRestaurantOrderService.processOrder(Number(id), status);
      ctx.body = { code: RESULT_CODE.SUCCESS, message: ret.message, data: null };
    } catch (error: any) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // （4）订单列表
  // query: scope=customer|restaurant, page, limit, status
  async listOrders() {
    const { ctx } = this;
    const { scope = 'customer', page = 1, limit = 50, status } = ctx.query as any;

    try {
      const data = await ctx.service.exclusiveRestaurantOrderService.listOrders({
        scope: scope as any,
        page: Number(page),
        limit: Number(limit),
        status: status as any,
      });
      ctx.body = { code: RESULT_CODE.SUCCESS, message: '获取成功', data };
    } catch (error: any) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }
}